﻿
Imports System.ComponentModel
Imports TBCC.MobileSystem.ProjectInfo
Imports TBCC.Net.Mail

''' <summary>
''' 提供邮件发送功能
''' </summary>
''' <remarks></remarks>
Public Class MailWorker

    Private worker As System.ComponentModel.BackgroundWorker
    Private Shared _instance As MailWorker
    Private timer As System.Timers.Timer
    Private _stop As Boolean = False
    Private mailer As TBCC.Net.Mail.Mailer

    ''' <summary>
    ''' 获取MialWorker实例
    ''' </summary>
    Public Shared ReadOnly Property Instance() As MailWorker
        Get
            If (_instance Is Nothing) Then _instance = New MailWorker()
            Return _instance
        End Get
    End Property

    ''' <summary>
    ''' 开始后台邮件
    ''' </summary>
    ''' <remarks>如果使用Stop 后，只能使用Resaume 恢复</remarks>
    Public Sub Start()
        If (Not _stop) Then
            timer.Start()
        End If
    End Sub
    ''' <summary>
    ''' 停止
    ''' </summary>
    ''' <remarks>只能使用Resaume 恢复</remarks>
    Public Sub [Stop]()
        _stop = True
        worker.CancelAsync()
    End Sub

    ''' <summary>
    ''' 回复
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Resaume()
        _stop = False
        If (Not worker.IsBusy) Then
            timer.Start()
        End If
    End Sub

    Private Sub New()
        worker = New System.ComponentModel.BackgroundWorker()
        worker.WorkerSupportsCancellation = True
        timer = New System.Timers.Timer(1000 * 60)

        AddHandler worker.DoWork, AddressOf DoWorker
        AddHandler worker.RunWorkerCompleted, AddressOf WorkerComplete

        AddHandler timer.Elapsed, AddressOf TimerElapsed

    End Sub

    Private Sub TimerElapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
        timer.Stop()
        worker.RunWorkerAsync()
    End Sub

    Private Sub DoWorker(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        ''========================================================
        '' 轮询所有的项目
        Dim lstP As List(Of CarProjectInfo) = CarProjectService.GetAllCarProjectInfo()
        If (lstP.Count > 0) Then
            For Each p As CarProjectInfo In lstP
                If (worker.CancellationPending) Then Exit Sub


                ''================================================
                '' 查询是否需要发送邮件
                Dim lstUnSent As List(Of ProjectMailSentStatus) = CarMailService.GetUnMailSent(p.ProId)
                If (lstUnSent.Count > 0) Then
                    If (worker.CancellationPending) Then Exit Sub
                    '' ============================================
                    '' 邮件收发信息
                    Dim mailitem As New MailItem
                    mailitem.TO = CarMailService.GetMailTo(p.ProId)
                    mailitem.From = CarMailService.GetMailFrom(p.ProId)

                    If (worker.CancellationPending) Then Exit Sub
                    If (mailitem.From Is Nothing) Then
                        Continue For
                    End If
                    If (mailitem.TO Is Nothing) Then
                        Continue For
                    End If
                    If (mailitem.TO.Count = 0) Then
                        Continue For
                    End If

                    '' 创建邮件对象
                    mailer = New Mailer(mailitem.From.Account, mailitem.From.Password, mailitem.From.SMTP, True)
                    Dim sts(mailitem.TO.Count - 1) As String
                    For i As Integer = 0 To mailitem.TO.Count - 1
                        sts(i) = mailitem.TO(i).TO
                    Next
                    Dim savepath As String = Application.StartupPath + "\Mails\" + p.CarProjectName
                    For Each pus As ProjectMailSentStatus In lstUnSent
                        If (worker.CancellationPending) Then Exit Sub

                        '' =======================================
                        '' 获取数据
                        Dim ds As DataSet = CarMailService.GetHistData(pus.ProjectID, pus.ParentId)
                        If (worker.CancellationPending) Then Exit Sub
                        Dim filename As String = DataExport.Export(pus.ProjectID, p.CarProjectName, pus.BeginTime, pus.EndTime, ds)
                        If (String.IsNullOrEmpty(filename)) Then
                            Continue For
                        End If
                        If (worker.CancellationPending) Then Exit Sub

                        '' 如果返回为 "NULL"
                        If (filename = "NULL") Then
                            filename = ""
                        End If
                        ''=========================================
                        '' 发送邮件          
                        Try
                            mailer.Send(sts, mailitem.From.Subject, mailitem.From.Body, filename, savepath, pus.BeginTime.ToString("yyyyMMddHHmmss") + "_" + pus.EndTime.ToString("yyyMMddHHmmss") + ".eml")
                            '' ========================================
                            '' 更新系统状态
                            CarMailService.SentMailFinished(pus.ProjectID, pus.ParentId)

                        Catch ex As Exception

                        Finally
                            If Not (String.IsNullOrEmpty(filename)) Then
                                System.IO.File.Delete(filename)
                            End If
                        End Try
                    Next
                End If
            Next
        End If
    End Sub



    Private Sub WorkerComplete(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
        If (Not _stop) Then
            timer.Start()
        End If
    End Sub
End Class
